package com.quick.android.view;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * 自动滚动的ViewPager <br>
 * 适用于Banner
 * 
 * @author caiby
 * 
 */
public class AutoScrollViewPage extends ViewPager implements Callback {
	private int time = 3000;
	private Timer mTimer;
	private TimerTask mTimerTask;
	private Handler mHandler = new Handler(this);
	private PagerAdapter mAdapter;

	public AutoScrollViewPage(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setDelayTime(int delaytime) {
		time = delaytime;
	}

	@Override
	public void setAdapter(PagerAdapter adapter) {
		super.setAdapter(adapter);
		mAdapter = adapter;
		resetTimer();
	}

	/**
	 * 重置定时器
	 */
	private void resetTimer() {
		if (mTimer != null) {
			mTimer.cancel();
		}

		if (getAdapter() != null && getAdapter().getCount() > 1) {
			mTimer = new Timer();
			mTimerTask = new TimerTask() {

				@Override
				public void run() {
					mHandler.obtainMessage().sendToTarget();
				}
			};
			mTimer.scheduleAtFixedRate(mTimerTask, time, time);
		}
	}

	/**
	 * 取消定时器
	 */
	private void cancelTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
		case MotionEvent.ACTION_MOVE:
			cancelTimer();
			break;
		case MotionEvent.ACTION_UP:
		default:
			resetTimer();
			break;
		}
		return super.onInterceptTouchEvent(event);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
		case MotionEvent.ACTION_MOVE:
			cancelTimer();
			break;
		case MotionEvent.ACTION_UP:
		default:
			resetTimer();
			break;
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onDetachedFromWindow() {
		cancelTimer();
		super.onDetachedFromWindow();
	}

	@Override
	public boolean handleMessage(Message msg) {
		if(getCurrentItem() == (mAdapter.getCount() - 1)){
			setCurrentItem(0, false);
		}else{
			setCurrentItem(getCurrentItem() + 1, true);
		}
		return true;
	}
}
